package ernest.uicompare;

import android.content.Context;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.Gravity;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;


public class UIWindowManager {
    private static final String TAG = "UIWindowManager";
    private static UIWindow uiWindow;
    private static boolean transparent = false;
    private static UIWindow.UIWindowActionListener listener = new UIWindow.UIWindowActionListener() {
        @Override
        public void onClick() {
//            transparentView(transparent);
//            transparent = !transparent;
            removeView(uiWindow.getContext());
        }

        @Override
        public void onLongClick() {
//            removeView(uiWindow.getContext());
        }
    };

    private static WindowManager mWindowManager;

    public static void addView(Context context, String filePath) {
        Log.d(TAG, "SHOW UI:" + filePath);
        if (uiWindow == null) {
            WindowManager windowManager = getWindowManager(context);
            int screenWidth = windowManager.getDefaultDisplay().getWidth();
            int screenHeight = windowManager.getDefaultDisplay().getHeight();
            uiWindow = new UIWindow(context);
            uiWindow.setUIBackgroundFile(filePath);
            transparentView(true);
            uiWindow.setUIWindowActionListener(listener);
            LayoutParams params = new LayoutParams();
            params.width = screenWidth;
            params.height = screenHeight;
            params.gravity = Gravity.LEFT | Gravity.TOP;
            params.type = LayoutParams.TYPE_APPLICATION_OVERLAY;
            params.format = PixelFormat.RGBA_8888;
            params.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
                    | LayoutParams.FLAG_NOT_FOCUSABLE;
            uiWindow.setLayoutParams(params);
            windowManager.addView(uiWindow, params);

        }
    }

    private static void transparentView(boolean transparent) {
        if (uiWindow != null) {
            uiWindow.transparentView(transparent);
        }
    }

    public static void removeView(Context context) {
        Log.d(TAG, "HIDE UI");
        if (uiWindow != null) {
            uiWindow.setUIWindowActionListener(null);
            WindowManager windowManager = getWindowManager(context);
            windowManager.removeView(uiWindow);
            uiWindow = null;
        }
    }

    private static WindowManager getWindowManager(Context context) {
        if (mWindowManager == null) {
            mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        }
        return mWindowManager;
    }
}